package cn.kgc.crowdfundingadmin.secrity;


import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MySecutityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权
        http.authorizeRequests()
                .antMatchers("/static/**", "/index")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()//设置未授权请求跳转到登录页面
                .loginPage("/admin/to/login/page.html")//指定登录页
                .permitAll()
                .loginProcessingUrl("/admin/secutity/do/login")//指定登录处理地址，不再使用原来的控制器
                .usernameParameter("loginAcct")//指定页面参数
                .passwordParameter("userPswd")
                .defaultSuccessUrl("/admin/to/main/page.html")//登录成功页面
                .failureUrl("/admin/to/login/page.html?error=true")//登录失败
                .and()
                .logout()//启动退出功能
                .logoutUrl("/admin/security/logout")//指定退出处理地址，不再使用原来的控制器
                .logoutSuccessUrl("/index")
                .and()
                .csrf()
                .disable()// 禁用CSRF功能，如果不禁用，只能发post请求退出，否则报错
    ;
    }

        @Override
        protected void configure (AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("test")
                    .password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                   ;

    }
}
